package cn.ac.iie.di.ban.ycl.wb.sname;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 张明诚
 * @version V1.0
 */
public class Preproccess {

    MongoClient mongoClient = null;
    private final String username;
    private final String password;
    private final String db;
    private final String host;
    private final String tablename;

    public Preproccess(String username, String password, String db,
            String host, String tablename) {
        this.username = username;
        this.password = password;
        this.db = db;
        this.host = host;
        this.tablename = tablename;
        init();
    }

    public String getUname(String uid) throws Exception {
        if(uid==null||uid.isEmpty()){
            throw new Exception("uid is empty or null!");
        }
        DB dbase = mongoClient.getDB(db);
        DBCollection collection = dbase.getCollection(tablename);
        BasicDBObject queryObject = new BasicDBObject("_id", uid);
        DBObject obj = collection.findOne(queryObject);
        if(obj==null){
            return null;
        }
        Object sname = obj.get("sname");
        return sname.toString();
    }

    private void init() {
        if (mongoClient == null) {
            MongoClientOptions.Builder build = new MongoClientOptions.Builder();
            build.connectionsPerHost(50);   //与目标数据库能够建立的最大connection数量为50
            build.threadsAllowedToBlockForConnectionMultiplier(50); //如果当前所有的connection都在使用中，则每个connection上可以有50个线程排队等待
            /*
             * 一个线程访问数据库的时候，在成功获取到一个可用数据库连接之前的最长等待时间为2分钟
             * 这里比较危险，如果超过maxWaitTime都没有获取到这个连接的话，该线程就会抛出Exception
             * 故这里设置的maxWaitTime应该足够大，以免由于排队线程过多造成的数据库访问失败
             */
            build.maxWaitTime(1000 * 60 * 2);
            build.connectTimeout(1000 * 60 * 1);    //与数据库建立连接的timeout设置为1分钟

            MongoClientOptions myOptions = build.build();
            //数据库连接实例
            MongoCredential credential = MongoCredential.createScramSha1Credential(username, db, password.toCharArray());
            List<MongoCredential> credentials = new ArrayList<>();
            credentials.add(credential);

            List<ServerAddress> seeds = new ArrayList<>();
            String[] hostArray = host.split("[;]");
            if (hostArray != null && hostArray.length > 0) {
                for (String service : hostArray) {
                    String[] serv = service.split(":");
                    if (serv != null && serv.length == 2) {
                        seeds.add(new ServerAddress(serv[0], Integer.parseInt(serv[1])));
                    }
                }
            }
            mongoClient = new MongoClient(seeds, credentials, myOptions);
        }
    }

}
